package com.zzg.lucene;

import java.io.IOException;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.RAMDirectory;

public class SearchLongPoint {

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		// 索引创建
		Directory directory = new RAMDirectory();
		IndexWriter indexWriter = new IndexWriter(directory, new IndexWriterConfig(new StandardAnalyzer()));
		Document document = new Document();
		Field longPoint = new LongPoint("age", 11);
		document.add(longPoint);
		longPoint = new StoredField("age", 11);
		document.add(longPoint);
		indexWriter.addDocument(document);
		longPoint = new LongPoint("age", 22);
		document = new Document();
		document.add(longPoint);
		longPoint = new StoredField("age", 22);
		document.add(longPoint);
		indexWriter.addDocument(document);
		indexWriter.close();
		
		// 检索
		IndexSearcher indexSearcher = new IndexSearcher(DirectoryReader.open(directory));
		// 精确查询
		Query query = LongPoint.newExactQuery("age", 11);
		ScoreDoc[] scoreDocs = indexSearcher.search(query, 10).scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println("精确查询：" + indexSearcher.doc(scoreDoc.doc));
		}
		// 范围查询，不包含边界
		query = LongPoint.newRangeQuery("age", Math.addExact(11, 1), Math.addExact(22, -1));
		scoreDocs = indexSearcher.search(query, 10).scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println("不包含边界：" + indexSearcher.doc(scoreDoc.doc));
		}
		// 范围查询，包含边界
		query = LongPoint.newRangeQuery("age", 11, 22);
		scoreDocs = indexSearcher.search(query, 10).scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println("包含边界：" + indexSearcher.doc(scoreDoc.doc));
		}
		// 范围查询，左包含，右不包含
		query = LongPoint.newRangeQuery("age", 11, Math.addExact(22, -1));
		scoreDocs = indexSearcher.search(query, 10).scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println("左包含右不包含：" + indexSearcher.doc(scoreDoc.doc));
		}
		// 集合查询
		query = LongPoint.newSetQuery("age", 11, 22, 33);
		scoreDocs = indexSearcher.search(query, 10).scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			System.out.println("集合查询：" + indexSearcher.doc(scoreDoc.doc));
		}
	}

}
